<!-- 用户积分兑换列表 -->
<template>
  <div class="pageListBox">
    <div class="cardAdmin">
      <div class="formNewAdmin" v-if="formshow">
        <div class="formSearch">
          <span class="namename">用户名</span>
          <el-input size="mini" style="flex: 3" v-model="form.username"></el-input>
        </div>
        <div class="souSuoYouCe">
          <el-button icon="el-icon-refresh" size="mini" class="white-button" @click="resetForm()">重置</el-button>
          <el-button class="black-button" icon="el-icon-search" size="mini" @click="get_data('btn')">搜索</el-button>
        </div>
      </div>
    </div>
    <div class="btnBoxList">
      <div class="btns">
        <el-button class="green-button" size="mini" icon="el-icon-plus" plain @click="addbtn()">Add</el-button>
        <el-button class="black-button" size="mini" icon="el-icon-refresh" plain @click="get_data()">刷新表格</el-button>
      </div>
      <div class="formbtns">
        <div style="max-width: 200px;height: 100%;;background-color: #f4f4f4;display: flex;">
          <div class="poipoi1">
            <el-dropdown @command="exportTable" class="popo1cli" trigger="click" placement="bottom">
              <span class="el-dropdown-link">
                <i style="font-size: 18px;" class="el-icon-download"></i>
                <i style="font-size: 14px;" class="el-icon-caret-bottom"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="json">JSON</el-dropdown-item>
                <el-dropdown-item command="xml">XML</el-dropdown-item>
                <el-dropdown-item command="csv">CSV</el-dropdown-item>
                <el-dropdown-item command="txt">TXT</el-dropdown-item>
                <el-dropdown-item command="word">Word</el-dropdown-item>
                <el-dropdown-item command="excel">Excel</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="poipoi2">
            <i style="font-size: 18px;cursor: pointer;" class=" el-icon-search" @click="showform"></i>

          </div>
        </div>
      </div>
    </div>
    <!-- 表格 -->
    <el-table v-table-resize  border highlight-current-row :data="tableData" cell-class-name="rowlist" class="x1919" ref="tableRef" size="mini"
      v-loading="table_loading">

      <el-table-column prop="id" fixed="left"  label="id" width="auto" align="center" min-width="80px">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="auto" align="center" min-width="140px">
      </el-table-column>
      <el-table-column prop="exchange_id" label="记录ID" width="auto" align="center" min-width="80px">
      </el-table-column>
      <el-table-column prop="spent_points" label="消耗积分" width="auto" align="center" min-width="120px">
      </el-table-column>
      <el-table-column prop="review_status" label="审核状态" width="auto" align="center" min-width="80px">
      </el-table-column>
      <el-table-column prop="illustrate" label="说明" width="auto" align="center" min-width="120px">
      </el-table-column>
      <el-table-column prop="apply_time" label="申请时间" width="auto" align="center" min-width="120px">
      </el-table-column>
      <el-table-column prop="exchange_time" label="兑换时间" width="auto" align="center" min-width="120px">
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button disabled @click="tableEditing(scope.row)" style="background-color: #18bc9c;border: none;color: #fff;"
            icon="el-icon-edit" type="info" plain size="mini"></el-button>
          <el-button @click="del_data(scope.row.id)" class="red-button"
            type="info" plain size="mini" v-if="scope.row.name !== 'admin'" icon="el-icon-delete"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="fenye11">
      <div style="display: flex;align-items: center;">{{ `当前第 ${currentPage} 页，每页 ${pagesize} 条记录` }}</div>
      <el-pagination background layout="prev, pager, next,total" :total="total" :page-size="pagesize"
        @current-change="current_change"></el-pagination>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-dialog-drag :close-on-click-modal="false" title="新增" top="35px" :visible.sync="dialogVisibleAdd"
       :before-close="beforeClose">
      <el-form :model="formAdd" :rules="rulesAdd" ref="formAdd" class="demo-formAdd">
        <el-form-item label="用户ID" prop="user_id">
          <el-input size="mini" v-model="formAdd.user_id"></el-input>
        </el-form-item>
        <el-form-item label="积分商品ID" prop="exchange_id">
          <el-input size="mini" v-model="formAdd.exchange_id"></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <div class="fbtns">
          <el-button class="purple-button" size="mini" @click="add_data" :loading="btnAdd" plain>确认新增</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-dialog-drag :close-on-click-modal="false" top="35px" title="更新" :visible.sync="dialogVisibleEdit"
       v-loading="dialogVisibleEditLoading" :before-close="beforeClose">
      <el-form :model="formEdit" :rules="rulesEdit" ref="formEdit" class="demo-formEdit">


      </el-form>
      <template slot="footer">
        <div class="fbtns">
          <el-button class="black-button" size="mini" plain @click="upd_data" :loading="btnEdit">确认修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
<script>
import {
  user_points_redemption_list,
  user_point_redemption_editor,
  new_user_point_redemption,
  delete_user_point_redemption,
} from "@/utils/api";
export default {
  name: "userIntegral",

  data() {
    return {
      table_loading: true,
      touristsspeak: [
        {
          value: 1,
          label: "是",
        },
        {
          value: 0,
          label: "否",
        },
      ],
      dialogVisibleEditLoading: false,
      dialogVisibleEdit: false,
      btnAdd: false,
      btnEdit: false,
      formshow: false,
      exportFormat: '',
      // 下拉框选中的列（存储 prop 值）
      selectedColumns: ['name'], // 默认选中姓名和日期

      // 所有可选的列配置
      allColumns: [
        { prop: 'last_login_time', label: '最后登录时间', width: '140px' }
      ],
      pagesize: 15,
      total: 0,
      options: [
        {
          value: 1,
          label: "是",
        },
        {
          value: 0,
          label: "否",
        },
      ],
      defaultProps: {
        children: "childs",
        label: "name",
      },
      menuProps: {
        children: "children",
        label: "label",
      },
      formAdd: {
        user_id: '',
        exchange_id: '',


      },
      formEdit: {
        id: '',
        user_id: '',
        exchange_id: '',
      },
      form: {
        username: "",
      },
      tableData: [
        { id: 1, date: '2023-01-01', group_name: '张三', status: '北京', permissions: '13800138000', name: 'name' },
        { id: 2, date: '2023-01-02', group_name: '李四', status: '上海', permissions: '13900139000', name: 'name' },
      ],
      dialogVisibleAdd: false,
      titles: "",
      name: "",
      nametype: "编辑",
      expandedKeys: [], // 控制哪些行默认展开
      menuData: [], //菜单列表
      userRoleList: [], //角色列表
      articlmenu: [], //文章列表
      draftsmenu: [], //草稿箱列表
      currentNodeData: [],
      currentDraftsKey: [],
      currentPage: 1,
      rulesEdit: {
        user_id: [
          { required: true, message: "请输入用户ID", trigger: "blur" },
        ],
        exchange_id: [
          { required: true, message: "请输入积分商品ID", trigger: "blur" },
        ],

      },
      rulesAdd: {
        user_id: [
          { required: true, message: "请输入用户ID", trigger: "blur" },
        ],
        exchange_id: [
          { required: true, message: "请输入积分商品ID", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    userRoleId() {
      const user = JSON.parse(localStorage.getItem("user"));
      return user ? user.role_id : null;
    },
    // 计算实际要显示的列
    visibleColumns() {
      return this.allColumns.filter(col =>
        this.selectedColumns.includes(col.prop)
      )
    }
  },
  watch: {
    // 当选择的列变化时，可以在这里添加额外逻辑
    selectedColumns(newVal) {
      console.log('当前显示的列：', newVal)
    },
  },
  mounted() {
    this.get_data();
  },

  methods: {
    setCheckedKeys(permissionIds) {
      console.log(permissionIds);
      if (!permissionIds) return;

      // 将字符串转换为数字数组
      const idsArray = permissionIds.split(',')
        .map(id => parseInt(id.trim()))
        .filter(id => !isNaN(id));

      if (idsArray.length > 0) {
        this.$refs.permissionTreeEdit.setCheckedKeys(idsArray);
      }
    },
    showform() {
      this.formshow = !this.formshow
    },
    get_time() {
      const now = new Date();
      const formatted = now.getFullYear() + '-' +
        String(now.getMonth() + 1).padStart(2, '0') + '-' +
        String(now.getDate()).padStart(2, '0') + ' ' +
        String(now.getHours()).padStart(2, '0') + ':' +
        String(now.getMinutes()).padStart(2, '0') + ':' +
        String(now.getSeconds()).padStart(2, '0');
      return formatted
    },
    // 新增打开
    addbtn() {
      this.dialogVisibleAdd = true;
      this.titles = "新增";
    },
    // 查询
    async get_data(btn) {
      if (btn) this.currentPage = 1
      this.table_loading = true; // 开始加载

      let params = new URLSearchParams();

      params.append('page', this.currentPage);
      params.append('page_size', this.pagesize);

      if (this.form.username) params.append('username', this.form.username);

      let data = `?${params.toString()}`;

      try {
        const res = await user_points_redemption_list(data);
        if (res.data && res.data.code == "200") {


          this.tableData = res.data.data.data;
          this.total = res.data.data.total_records;
        } else {
          this.$message.error(res?.data?.msg || "获取数据失败");
        }
      } catch (err) {
        console.error("获取数据失败:", err);
        this.$message.error("请求出错，请稍后再试");
      } finally {
        this.table_loading = false; // 不论成功失败都结束 table_loading
      }
    },
    // 新增
    async add_data() {

      this.btnAdd = true;
      try {
        const valid = await this.$refs.formAdd.validate();
        if (!valid) {
          this.$message.warning("表单验证未通过");
          return;
        }

        const fields = [
          'user_id', 'exchange_id'
        ];

        let data = {};

        for (const key of fields) {
          const value = this.formAdd[key];
          if (value !== '' && value !== null && value !== undefined) {
            data[key] = value;
          }
        }


        const res = await new_user_point_redemption(data);
        if (res && res.status == "200" && res.data.code == "200") {
          this.$message.success(res.data.message || '成功');


          this.get_data();
          this.dialogVisibleAdd = false;
        } else {
          this.$message.error(res?.data?.message || "操作失败");
        }
      } catch (err) {
        console.error(err);
        this.$message.error("请求失败，请稍后再试");
      } finally {
        this.btnAdd = false;
      }
    },
    // 更新
    async upd_data() {
      this.btnEdit = true;
      try {
        const valid = await this.$refs.formEdit.validate();
        if (!valid) {
          this.$message.warning("表单验证未通过");
          return;
        }

        const fields = [
          'id', 'user_id', 'exchange_id'
        ];

        const data = {};
        for (const key of fields) {
          const value = this.formEdit[key];
          if (value !== '' && value !== null && value !== undefined) {
            data[key] = value;
          }
        }

        const response = await user_point_redemption_editor(data);

        if (response.data && response.data.code == "200") {
          this.$message.success(response.data.msg);
          this.dialogVisibleEdit = false;
          this.get_data();
        } else {
          this.$message.warning(response?.data?.msg || "操作失败");
        }
      } catch (err) {
        console.error("更新失败:", err);
        this.$message.error("请求出错，请稍后再试");
      } finally {
        this.btnEdit = false;
      }
    },
    // 删除
    async del_data(id) {
      try {
        await this.$confirm("是否继续执行操作？", "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        });

        const res = await delete_user_point_redemption(id).catch((err) => {
          return console.error(err);
        });

        if (res && res.status == "200" && res.data.code == "200") {
          this.$message.success(res.data.msg);
          this.dialogVisibleAdd = false;
          this.get_data();
        } else {
          this.$message.error(res.data.msg);
        }
      } catch (error) {
        // 用户点击取消或关闭对话框
        console.error(error);
      }
    },
    // 关闭弹窗
    beforeClose() {
      this.dialogVisibleEdit = false
      this.dialogVisibleAdd = false

      this.formAdd = {
        user_id: '',
        exchange_id: '',
      }
      this.formEdit = {
        id: '',
        user_id: '',
        exchange_id: '',

      }
    },

    // 分页
    current_change(currentPage) {
      this.currentPage = currentPage;
      this.get_data();
    },
    // 重置
    resetForm() {
      this.form = {
        username: ""
      };
      this.currentPage = 1;
      this.get_data();
    },
    // 编辑打开
    tableEditing(row) {
      this.titles = "编辑";
      this.dialogVisibleEdit = true;

      this.formEdit.id = row.id;
      this.formEdit.exchange_id = row.exchange_id;
      this.formEdit.user_id = row.user_id;



    },
    exportTable(format) {
      switch (format) {
        case 'json':
          this.exportJSON();
          break;
        case 'xml':
          this.exportXML();
          break;
        case 'csv':
          this.exportCSV();
          break;
        case 'txt':
          this.exportTXT();
          break;
        case 'word':
          this.exportWord();
          break;
        case 'excel':
          this.exportExcel();
          break;
      }
    },
    exportJSON() {
      const jsonStr = JSON.stringify(this.tableData, null, 2);
      const blob = new Blob([jsonStr], { type: 'application/json' });
      this.downloadBlob(blob, 'table.json');
    },
    exportXML() {
      const xml = `<?xml version="1.0"?>\n<rows>\n` +
        this.tableData.map(item =>
          `  <row>\n` +
          `    <username>${item.username}</username>\n` +
          `    <age>${item.age}</age>\n` +
          `    <exchange_id>${item.exchange_id}</exchange_id>\n` +
          `    <id>${item.id}</id>\n` +
          `    <illustrate>${item.illustrate}</illustrate>\n` +
          `    <review_status>${item.review_status}</review_status>\n` +
          `    <spent_points>${item.spent_points}</spent_points>\n` +
          `  </row>`).join('\n') +
        `\n</rows>`;
      const blob = new Blob([xml], { type: 'application/xml' });
      this.downloadBlob(blob, 'table.xml');
    },
    exportCSV() {
      const headers = ['ID', '用户名', '产品ID', '说明', '审核状态'];
      const rows = this.tableData.map(item => [item.id, item.username, item.exchange_id, item.illustrate, item.review_status]);
      let content = headers.join(',') + '\n';
      rows.forEach(row => {
        content += row.join(',') + '\n';
      });
      const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
      this.downloadBlob(blob, 'table.csv');
    },
    exportTXT() {
      const headers = ['ID', '用户名', '产品ID', '说明', '审核状态'];
      const rows = this.tableData.map(item => [item.id, item.username, item.exchange_id, item.illustrate, item.review_status]);
      let content = headers.join('\t') + '\n';
      rows.forEach(row => {
        content += row.join('\t') + '\n';
      });
      const blob = new Blob([content], { type: 'text/plain;charset=utf-8;' });
      this.downloadBlob(blob, 'table.txt');
    },
    async exportWord() {
      const { default: HTMLDocx } = await import('html-docx-js/dist/html-docx');
      const html =
        `<table border="1" cellpadding="5" cellspacing="0"><tr><th>ID</th><th>用户名</th><th>产品ID</th><th>说明</th><th>审核状态</th></tr>` +
        this.tableData.map(item =>
          `<tr><td>${item.id}</td><td>${item.username}</td><td>${item.exchange_id}</td><td>${item.illustrate}</td><td>${item.review_status}</td></tr>`
        ).join('') +
        `</table>`;
      const blob = HTMLDocx.asBlob(html);
      this.downloadBlob(blob, 'table.docx');
    },
    async exportExcel() {
      const XLSX = await import('xlsx');
      const ws = XLSX.utils.json_to_sheet(this.tableData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([wbout], { type: 'application/octet-stream' });
      this.downloadBlob(blob, 'table.xlsx');
    },
    downloadBlob(blob, filename) {
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = filename;
      link.click();
      URL.revokeObjectURL(link.href);
    }
  },
};
</script>
<style>
.rowlist {
  padding: 6px !important;
}

.nbysm {
  flex: 2;
  text-align: right;
  line-height: 40px;
  font-weight: 700;
  font-size: 15px;
}

.souSuoYouCe {
  margin: 20px 0 0 auto;
  padding-bottom: 5px;
  padding-right: 10px;
}

.cell {
  font-size: 13px;
  white-space: nowrap !important;
}

.demo-table-expand {
  font-size: 0;
  margin-left: 10px;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
<style lang="less" scoped>
.namename {
  padding: 0 10px;
  text-align: right;
  line-height: 40px;
  font-weight: 700;
  font-size: 15px;
  display: flex;
  align-items: center;
}

.el-textarea {
  overflow: hidden;
  /* 隐藏滚动条 */
}

.pageListBox {
  width: 100%;
  // padding: 10px;
  // background-color: aquamarine;
  height: auto;
  // border: 1px #000 solid;

  .cardAdmin {
    position: relative;
    // height: 18%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin: 0;

    // border: #fafafa solid 1px;
    padding: 0 5px;
    margin-bottom: 2px;

    .formNewAdmin {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      padding: 0;
      align-self: baseline;
      padding-bottom: 10px;
      border-bottom: 1px #e3e3e3 solid;
    }

    .formSearch {
      width: 25%;
      min-width: 25%;
      margin-top: 20px;
      height: 30px;
      display: flex;
      justify-content: center;
    }
  }

  .btnBoxList {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;

    .formbtns {
      width: 50%;
      display: flex;
      justify-content: end;
      padding: 5px 10px;

      .qweqweasdasd {
        width: 75px;
        padding: 5px 10px;
        border: 1px #f4f4f4 solid;
      }

      .qweqweasdasd:hover {

        background-color: #e7e7e7;
        border: 1px #ccc solid;
      }


      .btnList22 {
        width: auto;
        height: 28px;
        color: #000;
        min-width: 50px;
        border-radius: 0px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;

        i {
          font-size: 18px;
        }
      }

    }

    .btns {
      width: 50%;
      display: flex;
      padding: 5px 10px;



    }


  }

  .pop-up-form {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 0;
    align-self: baseline;
    margin: 10px 0;
    justify-content: center;
    padding-right: 15px;

    .form-options {
      width: 100%;
      min-width: 100%;
      height: 40px;
      display: flex;
      justify-content: center;
      margin: 10px 0;
    }
  }
}
</style>
<style>
.cell {
  font-size: 13px;
  white-space: nowrap !important;
}

textarea {
  resize: none !important;
}

/* 子级样式 */
.child-row11 {
  background-color: #fcfcfc !important;
  color: #ff8718;
}

/* 父级样式 */
.parent-row11 {
  background-color: #ffffff;
  color: #000;
  font-weight: 500;
}

.parent-row11 .cell {
  font-size: 13px !important;
}

.el-dropdown-link {
  height: 100%;
  cursor: pointer;
  color: #000;
  font-weight: bold;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.fenye11 {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  padding: 4px 8px;
}



.el-pager li.active {
  background-color: #000 !important;
}

.setFomr {
  display: flex;
  align-items: center;
  padding: 10px 10px 0 10px;
}




.resetForm-button {
  background-color: #ffffff !important;
  border-color: #333 !important;
  color: #333 !important;
  font-size: 13px !important;
}

.resetForm-button:hover {
  background-color: #fff !important;
  border-color: #333 !important;
}
</style>
  